<template>
  <div class="homepage">
    <div class="homepage-header-bav">
      <div class="header-bav">
        <!-- <template #breadcrumb> </template> 这个是主页面导航条 -->
        <div class="homepage-header-bav-left">
          <div class="items-center">
            <el-avatar
                class="mr-3"
                :size="34"
                src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
            />
            <!-- <span class="text-large font-600 mr-3"> Title </span> -->
            <span class="text-sm mr-2" style="color: var(--el-text-color-regular)"> 个人主页</span>
            <el-icon><Message /></el-icon>
          </div>
        </div>
        <div class="homepage-header-bav-right">
          <div class="bav-button">
            <el-button @click="this.form={},addUserVisible=true">添加用户</el-button>
            <el-button type="primary" @click="this.form2={},checkUserVisible=true">查找用户</el-button>
            <el-button type="primary" @click="checkAlluser">部门管理</el-button>
          </div>
        </div>
      </div>
    </div>

    <div class="homepage-content">
      <div class="homepage-content-bav">
        <el-menu
            :default-active="activeIndex2"
            class="homepage-header-bav"
            mode="horizontal"
            background-color="#545c64"
            text-color="#fff"
            active-text-color="#ffd04b"
            @select=""
        >
          <div>
            <el-menu-item @click="checkAlluser">
              <template #title>全部</template>
            </el-menu-item>
          </div>
          <div v-for="(group,index) in departData">
            <el-menu-item @click="checkUserByDepartment(index)">
              <template #title>{{group}}</template>
            </el-menu-item>
          </div>
        </el-menu>
      </div>
      <div class="homepage-content-main">
        <el-table :data="tableData" style="width: 80%">
          <el-table-column prop="id" label="编号" width="100"></el-table-column>
          <el-table-column prop="account" label="账号"></el-table-column>
          <el-table-column prop="password" label="密码"></el-table-column>
          <el-table-column prop="name" label="姓名"></el-table-column>
          <el-table-column prop="power" label="权限等级" width="80"></el-table-column>
          <el-table-column prop="phone" label="电话"></el-table-column>
          <el-table-column prop="department_id" label="部门" width="150">
            <template #default="scope">
              <el-tag
                  :type="scope.row.department_id === '1'?'success':(scope.row.department_id === '2'?'success':(scope.row.department_id==='3'?'success':(scope.row.department_id==='4'?'success':(scope.row.department_id==='5'?'success':(scope.row.department_id==='6'?'success':'success')))))"
                  disable-transitions
              >{{ scope.row.department_id === '1'?departData['1']:(scope.row.department_id === '2'?departData['2']:(scope.row.department_id==='3'?departData['3']:(scope.row.department_id==='4'?departData['4']:(scope.row.department_id==='5'?departData['5']:(scope.row.department_id==='6'?departData['6']:departData['7']))))) }}
              </el-tag>
            </template>
          </el-table-column>

<!--          <el-table-column prop="department" label="部门"></el-table-column>-->
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button type="danger" size="big" @click="delUser(row.id)">删除</el-button>
              <el-button type="primary" size="big" @click="updateUser(row)">更新</el-button>
            </template>
          </el-table-column>

        </el-table>
        <el-pagination @size-change="sizeChange" @current-change="currentChange"
                       :current-page="page" :page-size="size" :page-sizes="pageSizes"
                       layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>

<!--      <div class="example-pagination-block">-->
<!--        <div class="example-demonstration"></div>-->
<!--        <el-pagination layout="prev, pager, next" :total="7*10" />-->
<!--      </div>-->

    <el-dialog
        title="新增用户"
        v-model="addUserVisible"
        width="30%"
        center>
      <el-form ref="form" :model="form" label-width="80px">

        <el-form-item label="账号">
          <el-col :span="13">
            <el-input v-model="form.account"></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="密码">
          <el-col :span="13">
            <el-input v-model="form.password"></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="名字">
          <el-col :span="13">
            <el-input v-model="form.name"></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="权限">
          <el-col :span="13">
            <el-input v-model="form.power"></el-input>
          </el-col>
        </el-form-item>


        <el-form-item label="电话">
          <el-col :span="13">
            <el-input v-model="form.phone"></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="部门">
          <el-radio-group v-model="form.department">
            <el-radio label='1'>办公室</el-radio>
            <el-radio label='2'>治安部</el-radio>
            <el-radio label='3'>交通管理部</el-radio>
            <el-radio label='4'>反恐部</el-radio>
            <el-radio label='5'>消防部</el-radio>
            <el-radio label='6'>人口管理部</el-radio>
            <el-radio label='7'>出入境部</el-radio>
<!--            <el-radio label=1>店员</el-radio>-->
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser(addUserVisible=false)">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
        title="查找用户"
        v-model="checkUserVisible"
        width="30%"
        center>
      <el-form ref="form2" :model="form2" label-width="80px">

        <el-form-item label="查询账号">
          <el-col :span="13">
            <el-input v-model="form2.account"></el-input>
          </el-col>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="checkUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="checkUser(checkUserVisible = false)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {onMounted, ref} from 'vue'
import { reactive, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import axios from "axios";
import {ElMessage} from "element-plus";
import {onUpdated} from "@vue/runtime-core";
const activeIndex = ref('1')
const activeIndex2 = ref('1')
const handleSelect = (key, keyPath) => {
  console.log(key, keyPath)
}

export default {
  setup() {
    const tableData = reactive([])
    const departmentData=reactive([])
    const data=reactive(({
      addUserVisible:false,
      checkUserVisible:false
    }))
    const departData=reactive({})

    //根据部门查找用户
    const checkUserByDepartment=async (department)=>{
      const { data:res }=await axios.post('minister/checkUserByDepartment',{
        department:(department)
      })
      if (res.code == 200) {
        // tableData.splice(0, tableData.length, ...res.data)
        tableData.splice(
            0,
            tableData.length,
            ...res.data.map((task) => ({
              ...task,
            }))
        )
        this.total=tableData.length
      }else {
        tableData.splice(0, tableData.length, )
      }
    }

    //删除用户
    const delUser=async (id)=>{
      const {data:res}=await axios.post('minister/deleteUser',{
        id:id
      })
      checkAllUser()
      console.log(id)
    }
    //更新用户信息
    // const updateUser=async (row)=>{
    //   form.account=row.account
    //   form.password=row.password
    //   form.name=row.name
    //   form.power=row.power
    //   form.phone=row.phone
    //   form.department=row.department
    //   console.log(form)
    //   // const {data:res}=await axios.post('minister/updateUser',{
    //   //
    //   // })
    // }
    //新增部门
    const addDepartment=async ()=>{
      const {data:res}=await axios.post('minister/addDepartment',{

      })
    }
    //查找所有部门
    const checkAllDepartment=async ()=>{
      const {data:res}=await axios.get('minister/checkAllDepartment')

        departmentData.splice(
          0,
            departmentData.length,
          ...res.data.map((task) => ({
            ...task,
          }))
        )
      let i=0
      while (i<departmentData.length){
        // departData[i]=departmentData[i].id
        // departData[i]=departmentData[i].department
        departData[departmentData[i].id]=departmentData[i].department
        i++
      }
      console.log(departData)
    }
    onMounted(checkAllDepartment);
    // onMounted(this.checkAlluser);
    // onUpdated(checkAllUser);
    return {
      ...toRefs(data),
      tableData,
      departmentData,
      departData,
      // checkAllUser,
      // checkUserByDepartment,
      // addUser,
      delUser,
      // updateUser,
      checkAllDepartment,
      // form,
    }
  },
  data(){
    return{
      page: 1, //第几页
      size: 5, //一页多少条
      total: 0, //总条目数
      pageSizes: [3, 5, 10, 20], //可选择的一页多少条
      allData:[],
      form:{
        id:'',
        account: '',
        password: '',
        name: '',
        power: '',
        phone: '',
        department: '',
      },
      form2:{
        account: ''
      }
      // addUserVisible:true,
    }
  },
  methods:{
    addUser(){
      // console.log(this.form.id)
      if(this.form.id!=undefined){
        this.$axios.post("minister/updateUser",this.form).then(res=>{
          console.log(res)
          if(res.data.code==200){
            ElMessage({
              message: '更新成功',
              type: 'success',
            })
            this.form={}
          }else{
            ElMessage({
              message: '更新失败',
              type: 'error',
            })
          }
          this.checkAlluser()
        })
        // this.checkAllUser();
      }else{
        this.$axios.post("minister/addUser",this.form).then(res=>{
          console.log(res.data)
          if(res.data.code==200){
            ElMessage({
              message: '添加成功',
              type: 'success',
            })
            this.form={}
          }else{
            ElMessage({
              message: '添加失败',
              type: 'error',
            })
          }
          this.checkAlluser()
        })
      }
    },
    checkUser(){
      this.$axios.post("minister/checkUserById", {
        account:this.form2.account
      }).then(res=>{
      console.log(res)
        if(res.data.code==200){
          ElMessage({
            message: '查找成功',
            type: 'success',
          })
          this.tableData.splice(
              0,
              this.tableData.length,
              ...res.data.data.map((task) => ({
                ...task,
              }))
          )
          // console.log(this.tableData)
          this.form2={}
        }else{
          ElMessage({
            message: '查找成功',
            type: 'error',
          })
        }
      })
    },
    updateUser(row){
      this.form.id=row.id
      this.form.account=row.account
      this.form.password=row.password
      this.form.name=row.name
      this.form.power=row.power
      this.form.phone=row.phone
      this.form.department=row.department_id
      // console.log(this.form.department)
      this.addUserVisible=true
    },
    checkAlluser(){
      this.allData=[]
      this.$axios.get("minister/checkAllUser", {
      }).then(res=>{

        // console.log(res.data.data)
        if(res.data.code==200){
          this.allData.splice(
              0,
              this.allData.length,
              ...res.data.data.map((task) => ({
                ...task,
              }))
          )
          this.total=this.allData.length
          this.getTabelData()
          this.form2={}
        }else{
          ElMessage({
            message: '失败',
            type: 'error',
          })
          this.getTabelData()
        }
      })

    },
    checkUserByDepartment(department){
      this.allData=[]
      this.$axios.post("minister/checkUserByDepartment", {
        department:department
      }).then(res=>{
        // console.log(this.allData.length,666666)
        if (res.data.code == 200) {
          // tableData.splice(0, tableData.length, ...res.data)
          this.allData.splice(
              0,
              this.allData.length,
              ...res.data.data.map((task) => ({
                ...task,
              }))
          )
          console.log(this.allData,6666666)
          this.total=this.allData.length
          this.getTabelData()
        }else {
          this.allData.splice(0, this.tableData.length, )
          this.total=this.allData.length
          this.getTabelData()
        }
      })
      this.getTabelData()
    },

    //获取表格数据，自行分页（splice）
    getTabelData() {

      let data=JSON.parse(JSON.stringify(this.allData))
      this.tableData = data.splice(
          (this.page - 1) * this.size,
          this.size
      );
      this.total=this.allData.length
    },
    //page改变时的回调函数，参数为当前页码
    currentChange(val) {
      console.log("翻页，当前为第几页", val);
      this.page = val;
      this.getTabelData();
    },
    //size改变时回调的函数，参数为当前的size
    sizeChange(val) {
      console.log("改变每页多少条，当前一页多少条数据", val);
      this.size = val;
      this.page = 1;
      this.getTabelData();
    },
  },
  beforeMount() {
    this.checkAlluser();
    // this.getTabelData();
  },
  created() {
    // this.getTabelData();
  },
}
</script>
<style>
/* .homepage{
  position: relative;
  margin: 0 auto;
  width: 1024px;
  height: 100%;
} */
.homepage {
  width: 100%;

  /* height: 50px; */
}
.homepage-header-bav {
  width: 100%;
  /* height: 50px;   这个地方一会儿要改一下*/
  background-color: #a39d9d;
  height: 50px;
}
.header-bav {
  position: relative;
  margin: 0 auto; /*居中对齐的一种方式*/
  width: 1226px;
  height: 100%;
}
.homepage-header-bav-left {
  position: absolute;
  left: 0;
  margin-left: 0;
  width: 750px;
  height: 100%;
}
.homepage-header-bav-right {
  position: absolute;
  width: 400px;
  height: 100%;
  right: 0;

}
.items-center{
  position: absolute;
  width: 100%;
  height: 100%;
  /* display: flex; */
  padding-left: 0;


}
.bav-button{
  width: 100%;
  height: 100%;
  align-items: center;
  display: flex;

}
.homepage-content{
  position: relative;
  margin: 0 auto;
  width: 1226px;
  height: 100%;

}
.example-pagination-block + .example-pagination-block {
  margin-top: 10px;
}
.example-pagination-block .example-demonstration {
  margin-bottom: 16px;
}
</style>
